<?php


namespace App\Http\Controllers\Sesame;


use App\Http\Controllers\Controller;


class ApiController extends Controller
{

    protected function respond($code, $data=[], $msg = ''): \Illuminate\Http\JsonResponse
    {
        $data and $this->parseNull($data);
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return response()->json($result);
    }

    protected function success($data=[], $msg = ''): \Illuminate\Http\JsonResponse
    {
        return $this->respond(200,$data, $msg);
    }

    protected function error($msg, $code = '422'): \Illuminate\Http\JsonResponse
    {
        return $this->respond($code,[], $msg);
    }

    private function parseNull(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$v) {
                $this->parseNull($v);
            }
        } elseif (null === $data) {
            $data = '';
        }
    }


}
